//
//  DSUploadTool.swift
//  Upload
//
//  Created by Wei Zhang on 2022/2/14.
//

import UIKit
import LFLiveKit_ReplayKit
class DSUploadTool: NSObject {
    @objc public static let shared = DSUploadTool()
    
    var session : LFLiveSession?
    var url : String?
    
    func prefareToStart(_ param : [String:Any]){
        if let url = param["url"] as? String{
            self.url = url
        }else{
            self.url = "rtmp://192.168.6.147/live/livestream"
        }
        let stream = LFLiveStreamInfo()
        stream.url = self.url
        self.uploadSession().startLive(stream)
    }
    
    func uploadSession() -> LFLiveSession{
        if let session = session {
            return session
        }else{
            let audioConfiguration = LFLiveAudioConfiguration.defaultConfiguration(for: .medium)
            audioConfiguration?.numberOfChannels = 2
            let videoConfiguration = LFLiveVideoConfiguration.defaultConfiguration(for: .low3, outputImageOrientation: .portrait)
            videoConfiguration?.videoFrameRate = 60
            videoConfiguration?.videoMaxFrameRate = 60
            videoConfiguration?.videoMinFrameRate = 30
            videoConfiguration?.autorotate = true
            
            session = LFLiveSession.init(audioConfiguration: audioConfiguration, videoConfiguration: videoConfiguration, captureType: .inputMaskAll)
            session?.delegate = self
            session?.showDebugInfo = true
            session?.adaptiveBitrate = true
            return session!
        }
    }
    
    func stop(){
        session?.stopLive()
    }
    
    @objc func sendAudioBuffer(_ buffer : CMSampleBuffer){
        session?.pushAudioBuffer(buffer)
    }
    
    @objc func sendAudioData(_ data : Data){
        session?.pushAudio(data)
    }
    
    func sendVideoBuffer(_ buffer : CMSampleBuffer){
        session?.pushVideoBuffer(buffer)
    }
}

extension DSUploadTool : LFLiveSessionDelegate{
    func liveSession(_ session: LFLiveSession?, liveStateDidChange state: LFLiveState) {
        switch state {
        case .ready:
            print("##################未连接##################")
        case .pending:
            print("##################连接中##################")
        case .start:
            print("##################已连接##################")
        case .stop:
            print("##################已断开##################")
        case .error:
            print("##################连接错误##################")
        case .refresh:
            print("##################刷新##################")
        @unknown default:
            print("##################error##################")
        }
    }
    
    func liveSession(_ session: LFLiveSession?, debugInfo: LFLiveDebug?) {
        
    }
    
    func liveSession(_ session: LFLiveSession?, errorCode: LFLiveSocketErrorCode) {
        print("##################errorCode:\(errorCode)##################")
    }
}
